<template>
  <div>
    <Title v-if="!hideTitle" title="统计图表" style="margin-bottom:20px;"/>
    <div :style="hideTitle?{paddingLeft: 0}:{}" class="charts-tab-main">
      <div class="main-title">图表分类TAB</div>
      <template v-if="!showMobilePage">
        <el-button v-if="hasRouteAuth('system:chart:read') || hasRouteAuth('system:chart:admin')" style="background:#fff;color:#406EFF;width:120px;padding:7px 0px;" type="primary" plain size="small" @click="toOpenTable">查看分类列表</el-button>
        <el-button v-if="hasRouteAuth('system:chart:add')" style="background:#fff;color:#406EFF;width:120px;padding:7px 0px;" type="primary" plain size="small" @click="addItem">添加分类</el-button>
      </template>
      <template v-else>
        <div class="mobile-link-btn" @click="toOpenTable">查看分类列表</div>
        <div class="mobile-link-btn mobile-btn-left" @click="addItem">添加分类</div>
      </template>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title :title="chartTitle" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="configForm"
          :rules="rules"
          :model="queryData"
          label-position="right"
          label-width="80px"
          class="setting-form">
          <el-form-item label="分类名称" prop="name">
            <el-input
              v-model="queryData.name"
              style="font-size: 13px;width:240px;"
              type="text"
              size="small"
              maxlength="20"
              placeholder="最多20个字符"/>
          </el-form-item>
          <el-form-item label="可见人员" prop="isAll">
            <el-radio-group v-model="queryData.isAll">
              <el-radio :label="1"><span style="font-size:13px;">全部</span></el-radio>
              <el-radio :label="0"><span style="font-size:13px;">指定</span></el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="!queryData.isAll">
            <el-form-item label="可见部门" prop="departmentList">
              <el-cascader
                ref="department-cascader"
                v-model="queryData.departmentList"
                :show-all-levels="false"
                :options="departmentAll"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                }"
                filterable
                collapse-tags
                class="department-all"
                size="small"
                placeholder="请选择部门"
                clearable
                @change="cascaderChanage"
              >
                <template slot-scope="{ data }">
                  <ToolTip v-if="data.name.length > 14" :content="data.name" class="inline-tag"/>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
            <el-form-item label="可见人员" prop="userList">
              <selectWithUserLoad
                ref="selectUser"
                v-model="queryData.userList"
                :hide-select-list="queryData.userList || []"
                :value-type="'object'"
                style="width:240px;"
                placeholder="请选择人员"
                key-name="id"
                label-name="userName"
                multiple
                filterable
                collapse-tags
                clearable
              />
            </el-form-item>
          </template>
          <el-form-item label="首页" prop="isFirstPage" class="is-first-page">
            <el-radio-group v-model="queryData.isFirstPage">
              <el-radio :label="1"><span style="font-size:13px;">是</span></el-radio>
              <el-radio :label="0"><span style="font-size:13px;">否</span></el-radio>
            </el-radio-group>
            <el-tooltip :open-delay="300" placement="top" effect="dark">
              <div slot="content">当前用户可见图表类型为首页，且位置值最小，<br>更新时间最新的将被设为用户唯一首页</div>
              <el-image :src="inHover ? tipHover : tip" class="tip-img" @mouseenter="changeImg(true)" @mouseleave="changeImg()"/>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="位置" prop="index" label-width="70px" style="padding-left:10px;">
            <el-input
              v-model="queryData.index"
              style="font-size: 13px;width:240px;"
              type="number"
              oninput="if(value>10000 )value=10000;if(value<0)value=0;if(value)value=Math.floor(value);if(value.toString().indexOf('.')>=0)value=Number(value.toString().replace('.',''))"
              size="small"
              maxlength="5"
              placeholder="请输入数字，越小位置靠前"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="状态" prop="isEnable" label-width="70px" style="padding-left:10px;">
            <el-radio-group v-model="queryData.isEnable">
              <el-radio :label="1"><span style="font-size:13px;">启用</span></el-radio>
              <el-radio :label="0"><span style="font-size:13px;">禁用</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="btn-container">
          <el-button :loading="btnLoading" type="primary" size="small" @click="handleOk">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="tableShow"
      :before-close="costTableClose"
      :append-to-body="false"
      class="large-common-dialog-size create-settle-dialog cost-config-dialog chart-dialog"
    >
      <div class="flex" style="margin-bottom:10px;">
        <Title title="图表分类管理" style="flex: unset;" />
        <div class="opeator-bar-checkbox" style="margin-left: 10px;">
          <el-checkbox v-model="isOnlyShowFirstPage" @change="handleChange">仅展示首页</el-checkbox>
        </div>
        <div style="flex: 1;text-align: right;">
          <PlainCreateBtn v-if="hasRouteAuth('system:chart:add')" @click="addItem">添加</PlainCreateBtn>
        </div>
      </div>
      <el-table
        v-loading="listloading"
        :data="listData.items"
        :max-height="tableHeight"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <el-table-column align="left" label="分类名称" width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.name" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="可见部门" width="130">
          <template slot-scope="scope">
            <div v-if="scope.row.isAll">全部</div>
            <ToolTip :content="scope.row.departmentName"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="可见人员" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.isAll">全部</div>
            <ToolTip v-else :content="scope.row.userListName"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="位置" width="70">
          <template slot-scope="scope">
            <div v-if="scope.row.index || scope.row.index === 0">{{ scope.row.index }}</div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" width="70">
          <template slot-scope="scope">
            <div v-if="scope.row.isEnable" class="enable-status"><span>启用</span></div>
            <div v-else class="disable-status"><span>禁用</span></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="首页" width="70">
          <template slot-scope="scope">
            <div v-if="scope.row.isFirstPage">是</div>
            <div v-else>否</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建人" >
          <template slot-scope="scope">
            <div v-if="scope.row.creator">{{ scope.row.creator }}</div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="更新时间" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.updateTime">{{ scope.row.updateTime | standardFormat }}</div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column v-if="hasRouteAuth('system:chart:edit') || hasRouteAuth('system:chart:delete')" :fixed="showMobilePage?false:'right'" align="left" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="hasRouteAuth('system:chart:edit')" type="text" @click="editItem(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
            <el-dropdown trigger="click">
              <div class="el-dropdown-link">
                <el-button class="button-text" type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
              </div>
              <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                <el-dropdown-item v-if="scope.row.isEnable" style="text-align: center" @click.native="toEditItem(scope.row.id, scope.row)">
                  <div>编辑图表</div>
                </el-dropdown-item>
                <el-dropdown-item style="text-align: center" @click.native="copyItem(scope.row)">
                  <div>复制</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('system:chart:delete')" style="text-align: center" @click.native="deleteItem(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div style="display:flex;justify-content:flex-end;margin-top:20px;">
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="listData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 组件
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getChartsTab, deleteChartsTab, getDepartmentAll, createChartsTab, editChartsTab } from '@/api/config';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { standardFormat } from '@/filters/date';
import { mapState } from 'vuex';

import tip from '@/assets/tishi.png';
import tipHover from '@/assets/tishi_hover.png';
import setting from '@/assets/setting.png';
export default {
  components: { Title, selectWithoutHttp, selectWithUserLoad },
  filters: { standardFormat },
  props: {
    hideTitle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateName = (msg) => {
      return (rule, value, callback) => {
        const name = this.queryData.name;
        if (!name || name === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    const validateType = (msg) => {
      return (rule, value, callback) => {
        const isAll = this.queryData.isAll;
        if (isAll === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      tip,
      tipHover,
      inHover: false,
      setting,
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateName('请输入分类名称') }],
        isAll: [{ required: true, trigger: 'change', validator: validateType('请选择可见人员') }]
      },
      queryData: {
        name: '',
        isAll: 1,
        index: '',
        isEnable: 1,
        userList: [],
        departmentList: [],
        isFirstPage: 0
      },
      page: 1,
      perPage: 20,
      listloading: false,
      listData: {
        items: []
      },
      dialogVisible: false,
      tableShow: false,
      btnLoading: false,
      tableHeight: '',
      departmentAll: [],
      chartStatus: 0, // 0添加 1编辑 2复制
      isOnlyShowFirstPage: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    chartTitle() {
      const titleOptions = ['添加图表分类', '编辑图表分类', '复制图表分类及内容'];
      return titleOptions[this.chartStatus];
    }
  },
  created() {
    this.getData();
    this.getDepartmentAll();
  },
  methods: {
    hasRouteAuth,
    changeImg(inHover = false) {
      this.inHover = inHover;
    },
    handleChange() {
      this.getData(true, this.isOnlyShowFirstPage);
    },
    getData(reset, isFirstPage = false) {
      if (reset) this.page = 1;
      this.listloading = true;
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      params.isFirstPage = isFirstPage ? 1 : 0;
      getChartsTab(params).then(res => {
        this.listloading = false;
        if (res.code === 200) {
          res.data.items.forEach(i => {
            if (i.departmentList) i.departmentName = i.departmentList.map(j => j.name).join('/');
            if (i.userList) i.userListName = i.userList.map(j => j.name).join('/');
          });
          this.listData = res.data;
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listloading = false;
      });
    },
    // 新增或编辑
    cascaderChanage() {
      console.log(this.queryData);
    },
    handleClose() {
      this.dialogVisible = false;
      this.queryData = {
        name: '',
        isAll: 1,
        index: '',
        isEnable: 1,
        userList: [],
        departmentList: [],
        isFirstPage: 0
      };
    },
    editItem(item) {
      if (this.$refs.configForm) this.$refs.configForm.clearValidate(); // 清空校验
      this.queryData = JSON.parse(JSON.stringify(item));
      if (this.queryData.userList && this.queryData.userList.length) {
        this.queryData.userList.forEach(i => {
          i.userName = i.name;
        });
      }
      if (item.departmentList && item.departmentList.length) {
        this.queryData.departmentList = item.departmentList.map(i => i.id);
      }
      this.chartStatus = 1;
      this.dialogVisible = true;
    },
    copyItem(item) {
      if (this.$refs.configForm) this.$refs.configForm.clearValidate();// 清空校验
      this.chartStatus = 2;
      this.queryData = JSON.parse(JSON.stringify(item));
      this.queryData.srcId = this.queryData.id;
      delete this.queryData.id;
      if (this.queryData.userList && this.queryData.userList.length) {
        this.queryData.userList.forEach(i => {
          i.userName = i.name;
        });
      }
      if (item.departmentList && item.departmentList.length) {
        this.queryData.departmentList = item.departmentList.map(i => i.id);
      }
      this.dialogVisible = true;
    },
    addItem() {
      this.chartStatus = 0;
      this.dialogVisible = true;
      if (this.$refs.configForm) this.$refs.configForm.clearValidate();// 清空校验
    },
    toEditItem(id, item) {
      const params = {
        tabId: id,
        edit: true
      };
      if (item.isFirstPage) params.isFirstPage = 1;
      const url = this.$router.resolve({
        name: 'dashboard',
        query: params
      });
      window.open(url.href, '_blank');
    },
    handleOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      if (!paramsObj.isAll && (!paramsObj.departmentList || paramsObj.departmentList.length === 0) && (!paramsObj.userList || paramsObj.userList.length === 0)) {
        ElMessage.error('请选择部门或人员');
        return;
      }
      if (paramsObj.userList && paramsObj.userList.length) {
        const userListIds = paramsObj.userList.map(i => i.id);
        paramsObj.userList = userListIds;
      }
      if (paramsObj.index) paramsObj.index = Number(paramsObj.index);
      this.$refs.configForm.validate(valid => {
        if (valid) {
          if (this.chartStatus === 0 || this.chartStatus === 2) {
            this.add(paramsObj);
          } else {
            this.edit(paramsObj);
          }
        } else {
          return false;
        }
      });
    },
    edit(params) {
      this.btnLoading = true;
      editChartsTab(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.getData(false, this.isOnlyShowFirstPage);
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      createChartsTab(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.isOnlyShowFirstPage = false;
          this.getData();
          ElMessage.success('请求成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    // 表格展示
    toOpenTable() {
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 3) / 5;
      this.tableShow = true;
    },
    costTableClose() {
      this.tableShow = false;
    },
    deleteItem(id) {
      this.$confirm('是否确定删除该图表分类？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteChartsTab({ id }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getData(true);
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData();
    },
    getDepartmentAll() {
      getDepartmentAll().then(res => {
        if (res.code === 200) {
          this.departmentAll = res.data;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
.btn-container {
  display: flex;
  justify-content: center;
}
.charts-tab-main {
  display: flex;
  padding-left: 13px;
  align-items: center;
  .main-title {
    font-size: 14px;
    font-weight: 600;
    line-height: 14px;
    color: #141C3D;
    margin-right: 32px;
  }
}
.overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.department-all {
  width: 240px;
  display: flex;
  align-items: center;
  height: 32px;
  &::v-deep {
    .el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
      display: flex;
      justify-content: center;
      align-items: baseline;
    }
    .el-cascader__tags {
      display: flex;
      align-items: center;
    }
  }
}
.is-first-page {
  display: flex;
  align-items: center;
  &::v-deep {
    .el-form-item__content {
      margin-left: 0 !important;
      display: flex;
      align-items: center;
    }
  }
}
.tip-img {
  display: flex;
  align-items: center;
  margin: -2px 0 0 8px;
  width: 14px;
  height: 14px;
}
.chart-dialog {
  ::v-deep {
    .el-dialog__body {
      padding-top: 16px !important;
    }
    .el-checkbox__label {
      padding-left: 4px;
    }
  }
  .enable-status, .disable-status {
    position: relative;
    span {
      margin-left: 8px;
    }
    &::before {
      content: '';
      width: 4px;
      height: 4px;
      position: absolute;
      left: 0;
      top: 10px;
      border-radius: 50%;
    }
  }
  .enable-status {
    &::before {
      background-color: green;
    }
  }
  .disable-status {
    &::before {
      background-color: red;
    }
  }
}
</style>
